// page/consultant/customer/addCustomer.js
const common = require('../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    params: {
      title: '',
      cover: '',
      content: '',
    },
    tipObj: {
      title: '请填写标题',
      cover: '请上传图片',
      content: '请填写正文',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  choosePhoto() {
    if (this.data.params.cover) return
    let that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['original'],
      success: function (res) {
        console.log(11, res)
        let temp = res.tempFiles[0] && res.tempFiles[0].tempFilePath;
        console.log(22, common.config.UploadFile)
        wx.uploadFile({
          url: common.config.UploadFile,
          filePath: temp,
          name: 'file',
          formData: {
            upload_type: 'local',
            file: temp
          },
          success: function (res) {
            console.log(113, res)
            let data = res.data && JSON.parse(res.data);
            if (data.code == 0) {
              let cover = data.data && data.data.url;
              that.setData({
                ['params.cover']: cover
              });
            } else {
              console.log(114, res.data)
              wx.hideLoading();
              let text = data.msg ? data.msg : "接口异常";
              wx.showToast({
                icon: "none",
                title: text,
              })
            }
          },
          fail: function (e) {},
          complete: function (e) {}
        });
      }
    });
  },
  textareas: function (e) {
    this.data.params.content = e.detail.value;
  },

  formSubmit(e) {
    wx.showLoading({
      title: "加载中",
      mask: true
    });
    let data = e.detail.value;
    let {
      tipObj = {},
        params = {}
    } = this.data;
    params = {
      ...params,
      ...data
    };

    for (let key in tipObj) {
      if (!params[key]) {
        wx.hideLoading();
        wx.showToast({
          title: tipObj[key],
          icon: "none"
        });
        return;
      }
    }
    console.log('params', params);
    common.getData_user(common.config.AddNews, params, 'post', res => {
      if (res.code != 0) {
        wx.hideLoading();
        wx.showToast({
          title: '发布失败',
          icon: "none"
        });
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '发布成功',
          icon: "none"
        });
        wx.navigateBack();
      }
    });
  },

});